import { useSearchParams } from 'react-router-dom'
import BookingRow from './BookingRow'
import Table from '../../ui/Table'
import Menus from '../../ui/Menus'
import { useBookings } from './useBookings'
import Spinner from '../../ui/Spinner'
import Pagination from '../../ui/Pagination.jsx'

function BookingTable() {
	const { bookings = [], isPending } = useBookings()
	const [searchParams] = useSearchParams()
	const status = searchParams.get('status') || 'all'

	// Filtering
	let filteredBookings = bookings
	if (status !== 'all') {
		filteredBookings = bookings.filter((booking) => booking.status === status)
	}

	// Sorting
	const sortBy = searchParams.get('sortBy') || 'startDate-asc'
	const [field, order] = sortBy.split('-')
	const modifier = order === 'asc' ? 1 : -1
	const sortedBookings = [...filteredBookings].sort((a, b) => {
		if (field === 'startDate') {
			return (
				(new Date(a[field]).getTime() - new Date(b[field]).getTime()) * modifier
			)
		}
		return (a[field] - b[field]) * modifier
	})

	if (isPending) return <Spinner />

	return (
		<Menus>
			<Table columns='0.6fr 2fr 2.4fr 1.4fr 1fr 3.2rem'>
				<Table.Header>
					<div>Cabin</div>
					<div>Guest</div>
					<div>Dates</div>
					<div>Status</div>
					<div>Amount</div>
					<div />
				</Table.Header>

				<Table.Body
					data={sortedBookings}
					render={(booking) => (
						<BookingRow
							key={booking.id}
							booking={booking}
						/>
					)}
				/>

				<Table.Footer>
					<Pagination count={sortedBookings.length} />
				</Table.Footer>
			</Table>
		</Menus>
	)
}

export default BookingTable
